using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using TerritoryGame.Application.Dtos;
using TerritoryGame.Application.Interfaces;
using TerritoryGame.Application.Commands;

namespace TerritoryGame.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class UserLevelController : ControllerBase
    {
        private readonly IAppUserLevelService _userLevelService;

        public UserLevelController(IAppUserLevelService userLevelService)
        {
            _userLevelService = userLevelService;
        }

        /// <summary>
        /// 获取全部用户的等级信息
        /// </summary>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResult<List<UserLevelDto>>>> GetAllUserLevels()
        {
            try
            {
                var list = await _userLevelService.GetAllUserLevelsAsync();
                return Ok(ApiResult.Success("获取用户等级列表成功", list));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }

        /// <summary>
        /// 获取等级排行榜（按经验或等级降序）
        /// </summary>
        [HttpGet("leaderboard")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResult<List<UserLevelDto>>>> GetLeaderboard()
        {
            try
            {
                var list = await _userLevelService.GetAllUserLevelsAsync();
                var ordered = list
                    .OrderByDescending(x => x.TotalExperience)
                    .ThenByDescending(x => x.CurrentLevel)
                    .Take(50)
                    .ToList();
                return Ok(ApiResult.Success("获取等级排行榜成功", ordered));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }


        /// <summary>
        /// 获取指定用户的等级信息
        /// </summary>
        [HttpGet("{userId}")]
        public async Task<ActionResult<ApiResult<UserLevelDto>>> GetUserLevel(Guid userId)
        {
            try
            {
                var userLevel = await _userLevelService.GetUserLevelAsync(userId);
                return Ok(ApiResult.Success("获取用户等级成功", userLevel));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }

        /// <summary>
        /// 获取指定用户的称号信息
        /// </summary>
        [HttpGet("{userId}/titles")]
        public async Task<ActionResult<ApiResult<List<TitleInfoDto>>>> GetUserTitles(Guid userId)
        {
            try
            {
                var titles = await _userLevelService.GetUserTitlesAsync(userId);
                return Ok(ApiResult.Success("获取用户称号成功", titles));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }

        /// <summary>
        /// 获取所有称号信息
        /// </summary>
        [HttpGet("all-titles")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResult<List<TitleInfoDto>>>> GetAllTitles()
        {
            try
            {
                var titles = await _userLevelService.GetAllTitlesAsync();
                return Ok(ApiResult.Success("获取所有称号成功", titles));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }

        /// <summary>
        /// 添加经验值
        /// </summary>
        [HttpPost("add-experience")]
        public async Task<ActionResult<ApiResult<LevelUpResultDto>>> AddExperience([FromBody] AddExperienceDto dto)
        {
            try
            {
                // 确保只能给自己添加经验值
                var currentUserId = GetCurrentUserId();
                if (dto.UserId != currentUserId)
                {
                    return Forbid();
                }

                var result = await _userLevelService.AddExperienceAsync(dto);
                return Ok(ApiResult.Success("添加经验成功", result));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }

        /// <summary>
        /// 更换称号
        /// </summary>
        [HttpPost("change-title")]
        public async Task<ActionResult<ApiResult>> ChangeTitle([FromBody] ChangeTitleDto dto)
        {
            try
            {
                // 确保只能更换自己的称号
                var currentUserId = GetCurrentUserId();
                if (dto.UserId != currentUserId)
                {
                    return Forbid();
                }

                var success = await _userLevelService.ChangeTitleAsync(dto);
                if (success)
                {
                    return Ok(ApiResult.Success("称号更换成功"));
                }
                else
                {
                    return BadRequest(ApiResult.Failed(400, "称号更换失败，可能未解锁该称号"));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResult.Failed(400, ex.Message));
            }
        }

        

        

        private Guid GetCurrentUserId()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
            {
                throw new UnauthorizedAccessException("用户未登录或用户ID无效");
            }
            return userId;
        }
    }
}
